package com.shawn.spring.boot.jpa.service.impl;

import com.shawn.spring.boot.jpa.entity.User;
import com.shawn.spring.boot.jpa.repository.UserRepository;
import com.shawn.spring.boot.jpa.service.UserService;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author shawn
 * @since 2020/8/31
 */
@Service
public class UserServiceImpl implements UserService {

  @Autowired private UserRepository repository;

  @Override
  @Transactional(rollbackFor = RuntimeException.class)
  public void insertThenRollback(User user) {
    repository.save(user);
    throw new RuntimeException();
  }

  @Override
  public void invokeInsertThenRollback(User user) throws RuntimeException {
    insertThenRollback(user);
  }

  @Override
  public List<User> findAll() {
    Iterator<User> iterator = repository.findAll().iterator();
    List<User> users = new ArrayList<>();
    while (iterator.hasNext()) {
      User next = iterator.next();
      users.add(next);
    }
    return users;
  }
}
